package com.c212.manager.config;

import com.c212.manager.bean.PermissionEntity;
import com.c212.manager.bean.RoleEntity;
import com.c212.manager.bean.UserInfoEntity;
import com.c212.manager.repository.UserInfoRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoRepository userInfoRepository;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserInfoEntity user = (UserInfoEntity) principals.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissionList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        Set<RoleEntity> roleSet = user.getRoles();

//        if (CollectionUtils.isNotEmpty(roleSet)) {
        if (roleSet != null && roleSet.size() > 0) {
            for (RoleEntity role : roleSet) {
                roleNameList.add(role.getRname());
                Set<PermissionEntity> permissionSet = role.getPermissions();
//                if (CollectionUtils.isNotEmpty(permissionSet)) {
                if (permissionSet != null && permissionSet.size() > 0) {
                    for (PermissionEntity permission : permissionSet) {
                        permissionList.add(permission.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        return info;
    }

    // 认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String loginId = usernamePasswordToken.getUsername();
        UserInfoEntity user = userInfoRepository.findByLoginId(loginId);
        return new SimpleAuthenticationInfo(user, user.getLoginPwd(), this.getClass().getName());
    }
}
